package com.js.foodordersystem.exception;

import com.js.foodordersystem.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;



@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * springbootstarter自带的参数校验异常
     * 返回第一个参数异常的信息
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result handleValidation(BindException e) {
        log.error("数据校验出现问题");
        return Result.failure(e.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
    }

    /**
     * javax参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public Result handleVaildException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError)->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        log.error("数据校验出现问题{}，异常类型：{}，异常数据：{}",e.getMessage(),e.getClass(),errorMap);
        return Result.failure("参数校验失败"+errorMap);
    }

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(RRException.class)
    public Result handleRRException(RRException e){
        StackTraceElement[] stackTrace = e.getStackTrace();
        log.error("处理自定义异常：---> 异常类:{},异常方法:{},异常行号:{},异常信息:{}",stackTrace[0].getClassName(),stackTrace[0].getMethodName(),stackTrace[0].getLineNumber(),e.getMessage());
        return Result.failure("网络繁忙,请稍后再试");
    }

    /**
     * 处理运行时异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException e){
        StackTraceElement[] stackTrace = e.getStackTrace();
        log.error("运行时异常：---------{}",e.getMessage());
        log.error("运行时异常定位信息：---> 异常类:{},异常方法:{},异常行号:{},异常信息:{}",stackTrace[0].getClassName(),stackTrace[0].getMethodName(),stackTrace[0].getLineNumber(),e.getMessage());
//        return Result.failure(e.getMessage());
        return Result.failure("运行时异常");
    }

    /**
     * 错误信息
     * @param throwable
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public Result handleException(Throwable throwable){
        log.error("错误异常-------{}",throwable);
        return Result.failure();
    }

    /**
     * 未知异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        log.error("未知异常信息-------{}",e.getMessage());
        return Result.failure();
    }

}
